package com.bkhech.netty.httpwebsocket.server;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.bkhech.netty.httpwebsocket.pojo.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.time.LocalDateTime;

/**
 * WebSocket Server
 *
 * @author guowm
 * @date 2024/3/30
 */
public class WebSocketServer {
    private final ChannelGroup channelGroup = ClientChannelGroup.getInstance();

    private final int port;

    public WebSocketServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            //因为 WebSocket 是基于http协议，使用http的编码和解码器
                            pipeline.addLast(new HttpServerCodec());
                            //是以块方式写，添加ChunkedWriteHandler处理器
                            pipeline.addLast(new ChunkedWriteHandler());

                            /*
                                1.http数据在传输过程中是分段，HttpObjectAggregator就是可以将多个段聚合，这就解释了当浏览器发送大量数据时，会发出多次http请求的问题
                                2.这个聚合器主要是将 HttpMessage 聚合成http为一个完整的报文，即 FullHttpRequest/FullHttpResponse
                             */
                            pipeline.addLast(new HttpObjectAggregator(65536));

                            /*
                            1.对应websocket，它的数据是以帧（frame）形式传递
                            2.可以看到WebSocketFrame下面的六个子类
                            3.浏览器请求时，ws://localhost:8080/hello表示请求的url
                            4.WebSocketServerProtocolHandler核心功能是将http协议升级为ws协议，处理握手操作，保持长连接
                            5.是通过一个状态码101
                            6. 此 Handler 会帮我们处理一些比较复杂的繁重的操作。
                                会处理一些握手操作：handShaking（close,ping,pong），ping + pong = 心跳
                                对于 WebSocket 来说，数据都是以 frames 进行传输的，不同的数据类型所对应的 frames 也都不同
                             */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));

                            //自定义的handler，处理业务逻辑
                            pipeline.addLast(new WebSocketHandler());
                        }
                    });

            ChannelFuture f = b.bind(port).sync();
            System.out.println("服务器启动成功！");
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new WebSocketServer(8080).run();
    }

    public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame inputMsg) throws Exception {
            System.out.println("服务器收到消息 " + inputMsg.text());
            // 获得客户端传输过来的消息
            String content = inputMsg.text();

            // 解析客户端发过来的消息
            final Request<Message> request = JSONUtil.toBean(content, Request.class);
            assert request != null;

            final MsgType msgType = request.getMsgType();

            Channel currentChannel = ctx.channel();
            String currentChannelId = currentChannel.id().asLongText();
            request.setExtend(currentChannelId);
            request.setChannel(currentChannel);

            switch (msgType) {
                case CONNECT_INIT:
                    final Message message = request.getMessage();
                    message.setMsgTime(LocalDateTime.now());
                    break;
                case KEEPALIVE:
                    // 保持心跳
                    final Message keepaliveMessage = request.getMessage();
                    keepaliveMessage.setMsgTime(LocalDateTime.now());
                    break;
                case CHAT:
                    Request<ChatMessage> chatRequest = JSONUtil.toBean(content, new TypeReference<>() {}, false);
                    final ChatMessage chatMessage = chatRequest.getMessage();

                    // 如何客户端没有传消息id，主动设置一个，可用于日志追踪
                    if (StrUtil.isEmpty(chatMessage.getMsgId())) {
                        chatMessage.setMsgId(SnowFlakeUtil.getInstance().nextIdStr());
                    }

                    // 设置消息时间
                    chatMessage.setMsgTime(LocalDateTime.now());

                    request.setMessage(chatMessage);
                    break;
                default:
                    // 关闭无法识别的无效链接
                    currentChannel.close();
                    return;
            }

            // 处理不同类型的消息
            MessageHandlerStrategy.handleMsgByType(request);
        }

        //当web客户端连接后，触发方法
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            Channel currentChannel = ctx.channel();
            String currentChannelId = currentChannel.id().asLongText();
            System.out.println("客户端建立连接，channel对应的长id为: " + currentChannelId);
            // 获得客户端的channel，存入到ChannelGroup中管理
            channelGroup.add(currentChannel);
            System.out.println("handlerAdded 被调用 " + ctx.channel().remoteAddress());
        }

        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            Channel currentChannel = ctx.channel();
            String currentChannelId = currentChannel.id().asLongText();
            System.out.println("客户端关闭连接，channel对应的长id为: " + currentChannelId);
            // 移除多余的会话
            String userId = UserChannelCache.getUserIdByChannelId(currentChannelId);
            UserChannelCache.removeUselessChannels(userId, currentChannelId);
            channelGroup.remove(currentChannel);
            System.out.println("handlerRemoved 被调用 " + ctx.channel().remoteAddress());
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("异常发生: ");
            cause.printStackTrace();
            ctx.close();
        }
    }
}
